<template>
  <List :loading="loading" @load="loadMoreAsync" :finished="noMore">
    <slot v-for="(item, index) in dataList" :key="index" name="item" :data="item"></slot>
  </List>
</template>

<script setup lang="tsx">
import { List } from 'vant'
import { DataType, useLoadMore } from 'vue-request'

interface Pagination {
  pageSize: number
  pageNum: number
}

interface Props {
  request: (pagination: Pagination) => Promise<any>
  autoLoad?: boolean
  pageSize?: Pagination['pageSize']
}

const props = withDefaults(defineProps<Props>(), {
  autoLoad: true,
  pageSize: 15,
})

const servers = async (data?: DataType) => {
  const pageNum = data?.pageNum + 1 || 1
  const { rows, total } = await props.request({
    pageNum,
    pageSize: props.pageSize,
  })

  return {
    list: rows,
    total: total || rows.length,
    pageNum,
  }
}

const { dataList, loading, noMore, refresh, loadMoreAsync } = useLoadMore(servers, {
  manual: !props.autoLoad,
  throttleInterval: 800,
  isNoMore(data) {
    return data ? data.list?.length >= data.total : true
  },
})

defineExpose({
  refresh,
})
</script>
